package com.toocms.jinjuhang.ui.mine.bank_card

import android.app.Application
import android.text.TextUtils
import androidx.databinding.Observable
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.StringUtils
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.UploadType
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.GetBankData
import com.toocms.jinjuhang.data.center.IsRealData
import com.toocms.jinjuhang.data.system.UploadData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger
import com.toocms.tab.widget.picker.builder.TimePickerBuilder
import java.text.SimpleDateFormat
import java.util.Calendar

class EditBankCardModel(application: Application) : BaseViewModel<BaseModel>(application) {
    var cardFId: String = ""
    var cardBId: String = ""
    var logo: String = ""
    val dataFormat = "yyyy-MM-dd"
    val calendar by lazy {
        Calendar.getInstance()
    }
    val typeObservableField = ObservableField<String>(Constants.Extra.BANK_TYPE_PERSONAGE)
    val isRealObservableField = ObservableBoolean(false) //是否实名认证
    val isLongTimeObservableField = ObservableBoolean(false) //是否长期
    val realNameObservableField = ObservableField<String>()
    val mobileObservableField = ObservableField<String>()
    val cardNoObservableField = ObservableField<String>()
    val bankNameObservableField = ObservableField<String>()
    val branchNameObservableField = ObservableField<String>()
    val cardFObservableField = ObservableField<String>()
    val cardBObservableField = ObservableField<String>()
    val cardStartObservableField = ObservableField<String>()
    val cardEndObservableField = ObservableField<String>()
    val accountNameObservableField = ObservableField<String>()
    val bankCardNoObservableField by lazy {
        ObservableField<String>().apply {
            addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
                override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                    val cardCode = get()
                    if (cardCode.isNullOrEmpty() || 14 > cardCode.length) {
//                        bankNameObservableField.set("")
                        logo = ""
                        return
                    }
                    val params = mutableMapOf<String, String?>()
                    params["member_id"] = UserRepository.user.member_id
                    params["cardId"] = cardCode
                    requestData(Urls.Center.GET_BANK,
                        params,
                        resultClass = GetBankData::class.java,
                        result = {
//                            bankNameObservableField.set(it.bank_name)
                            logo = it.icon ?: ""
                        },
                        error = {
//                            bankNameObservableField.set("")
                            logo = ""
                        })
                }

            })
        }
    }

    val startDateClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectedTime(1)
    })

    val endDateClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectedTime(2)
    })

    val individualClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        typeObservableField.set(Constants.Extra.BANK_TYPE_PERSONAGE)
    })
    val enterpriseClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        typeObservableField.set(Constants.Extra.BANK_TYPE_ENTERPRISE)
    })

    val idCardFrontalClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        upload(UploadType.ID_CARD_FRONTAL)
    })

    val idCardBackClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        upload(UploadType.ID_CARD_BACK)
    })

    val longTimeClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        isLongTimeObservableField.set(!isLongTimeObservableField.get())
    })

    val confirmClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["type"] = typeObservableField.get()
        params["real_name"] =
            if (isRealObservableField.get() && Constants.Extra.BANK_TYPE_PERSONAGE == typeObservableField.get()) "" else realNameObservableField.get()
        params["mobile"] = mobileObservableField.get()
        params["card_no"] =
            if (isRealObservableField.get() && Constants.Extra.BANK_TYPE_PERSONAGE == typeObservableField.get()) "" else cardNoObservableField.get()
        params["bank_card_no"] = bankCardNoObservableField.get()
        params["bank_name"] = bankNameObservableField.get()
        params["branch_name"] = branchNameObservableField.get()
        params["logo"] = logo
        params["card_f"] =
            if (isRealObservableField.get() && Constants.Extra.BANK_TYPE_PERSONAGE == typeObservableField.get()) "" else cardFId
        params["card_b"] =
            if (isRealObservableField.get() && Constants.Extra.BANK_TYPE_PERSONAGE == typeObservableField.get()) "" else cardBId
        params["card_start"] =
            if (isRealObservableField.get() && Constants.Extra.BANK_TYPE_PERSONAGE == typeObservableField.get()) "" else {
                if (isLongTimeObservableField.get()) "长期" else cardStartObservableField.get()
            }
        params["card_end"] =
            if (isRealObservableField.get() && Constants.Extra.BANK_TYPE_PERSONAGE == typeObservableField.get()) "" else {
                if (isLongTimeObservableField.get()) "长期" else cardEndObservableField.get()
            }
        params["account_name"] = accountNameObservableField.get()
        requestData(Urls.Center.ADD_BANK, params, resultClass = String::class.java, result = {
            showToast(it)
            Messenger.getDefault().sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_BANK)
            finishFragment()
        })
    })

    init {
        requestData(
            Urls.Center.IS_REAL,
            mapOf(Pair("member_id", UserRepository.user.member_id)),
            resultClass = IsRealData::class.java,
            result = {
                isRealObservableField.set("1" == it.is_real)
            })
    }


    /**
     * 上传图片
     *
     * @param type
     */
    fun upload(type: UploadType) {
        startSelectSignImageAty(
            object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    result?.apply {
                        if (isEmpty()) return@apply
                        val imagePath = this[0].realPath
//                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) this[0].androidQToPath
//                            else this[0].cutPath
                        requestData(Urls.System.UPLOAD,
                            filePaths = mapOf(Pair("image0", imagePath)),
                            resultClass = UploadData::class.java,
                            isShowLoading = true,
                            result = {
                                it.list?.apply {
                                    if (isEmpty()) return@requestData
                                    val item = this[0]
                                    when (type) {
                                        UploadType.ID_CARD_FRONTAL -> {
                                            cardFId = item.id ?: ""
                                            cardFObservableField.set(item.abs_url)
                                        }

                                        UploadType.ID_CARD_BACK -> {
                                            cardBId = item.id ?: ""
                                            cardBObservableField.set(item.abs_url)
                                        }

                                        else -> {}
                                    }
                                }

                            })
                    }
                }

                override fun onCancel() {

                }

            }, 27, 19
        )
    }

    /**
     * 选择时间
     *
     * @param type 1(开始时间),2(结束时间)
     */
    private fun selectedTime(type: Int) {
        val dataFormat = SimpleDateFormat(this@EditBankCardModel.dataFormat)
        TimePickerBuilder(
            ActivityUtils.getTopActivity()
        ) { date, v ->
            when (type) {
                1 -> {
                    cardStartObservableField.set(dataFormat.format(date))
                }

                2 -> {
                    cardEndObservableField.set(dataFormat.format(date))
                }
            }
        }.run {
            setTitleText(StringUtils.getString(R.string.str_date))
            setDividerColor(0x00000000)
            setLabel("", "", "", "", "", "")
            val startDate = cardStartObservableField.get()
            val endDate = cardEndObservableField.get()
            when (type) {
                1 -> {
                    if (!TextUtils.isEmpty(startDate)) {
                        calendar.time = dataFormat.parse(startDate)
                    }
                }

                2 -> {
                    if (!TextUtils.isEmpty(endDate)) {
                        calendar.time = dataFormat.parse(endDate)
                    }
                }
            }
            setDate(calendar)
            build()
        }.show()
    }

}